import React, { useState, useEffect, useRef } from 'react';
import ParameterCalculator from '../services/ParameterCalculator';
import './TDCAnalyzer.css';

const TDCAnalyzer = ({ dicomData, markers, enableInvert = true, frameRange = { start: 1, end: 1 }, onChartDataUpdate }) => {
  const canvasRef = useRef(null);
  const containerRef = useRef(null);
  const [chartData, setChartData] = useState([]);
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  
  // 初始化参数计算器
  const parameterCalculator = useRef(new ParameterCalculator()).current;

  // 监听图像翻转设置变化
  useEffect(() => {
    console.log('TDC分析器图像翻转设置:', enableInvert ? '启用' : '禁用');
  }, [enableInvert]);

  // 监听容器大小变化
  useEffect(() => {
    const updateSize = () => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        const newWidth = Math.max(300, rect.width - 32); // 减去padding
        const newHeight = Math.max(200, rect.height - 32);
        
        console.log('TDC容器尺寸更新:', { width: newWidth, height: newHeight });
        
        setContainerSize(prev => {
          if (prev.width !== newWidth || prev.height !== newHeight) {
            return { width: newWidth, height: newHeight };
          }
          return prev;
        });
      }
    };

    // 初始设置
    setTimeout(updateSize, 100);
    
    const resizeObserver = new ResizeObserver(updateSize);
    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }

    window.addEventListener('resize', updateSize);
    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', updateSize);
    };
  }, []);

  // 当标记或图像数据变化时重新计算TDC数据
  useEffect(() => {
    console.log('TDC数据变化检测:', { 
      hasDicomData: !!dicomData, 
      markersCount: markers.length,
      imageCount: dicomData?.images?.length,
      frameRange: frameRange
    });
    
    // 确保所有标记都有可见性状态
    const markersWithVisibility = markers.map(marker => ({
      ...marker,
      visible: marker.visible !== undefined ? marker.visible : true
    }));
    
    if (dicomData && dicomData.images && markersWithVisibility.length > 0) {
      calculateTDCData();
    } else {
      const emptyData = [];
      setChartData(emptyData);
      
      // 通知外部组件chartData已清空
      if (onChartDataUpdate) {
        onChartDataUpdate(emptyData);
      }
    }
  }, [dicomData, markers, frameRange]);

  // 当图表数据或容器大小变化时重绘图表
  useEffect(() => {
    console.log('图表重绘检测:', { 
      chartDataCount: chartData.length, 
      containerWidth: containerSize.width,
      containerHeight: containerSize.height
    });
    
    if (chartData.length > 0 && containerSize.width > 0 && containerSize.height > 0) {
      requestAnimationFrame(() => {
        drawChart();
      });
    }
  }, [chartData, containerSize]);

  // 从图像URL获取像素数据的辅助函数
  const getPixelDataFromImage = async (imageUrl) => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      
      img.onload = () => {
        try {
          // 创建临时canvas来提取像素数据
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          
          canvas.width = img.width;
          canvas.height = img.height;
          
          // 绘制图像到canvas
          ctx.drawImage(img, 0, 0);
          
          // 获取像素数据
          const imageData = ctx.getImageData(0, 0, img.width, img.height);
          const pixelData = imageData.data; // RGBA格式
          
          // 转换为灰度值
          const grayPixelData = new Uint8Array(img.width * img.height);
          for (let i = 0; i < grayPixelData.length; i++) {
            const r = pixelData[i * 4];
            const g = pixelData[i * 4 + 1];
            const b = pixelData[i * 4 + 2];
            // 使用标准灰度转换公式
            grayPixelData[i] = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
          }
          
          resolve({
            pixelData: grayPixelData,
            width: img.width,
            height: img.height
          });
        } catch (error) {
          reject(error);
        }
      };
      
      img.onerror = () => {
        reject(new Error('图像加载失败'));
      };
      
      img.src = imageUrl;
    });
  };

  // 缓存像素数据
  const [pixelDataCache, setPixelDataCache] = useState(new Map());
  // 缓存像素数据的最大值，用于图像翻转计算
  const [pixelDataMaxValues, setPixelDataMaxValues] = useState(new Map());

  // 获取像素值 - 改进版本，支持多种数据格式
  const getPixelValue = async (imageData, x, y) => {
    try {
      if (!imageData) {
        console.warn('图像数据为空');
        return 0;
      }

      // 调试：显示图像数据结构
      if (x === 0 && y === 0) { // 只在第一个像素时输出，避免太多日志
        console.log('图像数据结构:', {
          hasPixelData: !!imageData.pixelData,
          hasGetPixelData: typeof imageData.getPixelData === 'function',
          hasDataSet: !!imageData.dataSet,
          hasDataSetPixelData: !!(imageData.dataSet && imageData.dataSet.pixelData),
          hasDataset: !!imageData.dataset,
          hasImageId: !!imageData.imageId,
          width: imageData.columns || imageData.width,
          height: imageData.rows || imageData.height,
          keys: Object.keys(imageData)
        });
      }

      // 尝试从不同的属性获取像素数据
      let pixelData = null;
      let width = 256;
      let height = 256;

      // 检查不同的数据结构
      if (imageData.pixelData) {
        pixelData = imageData.pixelData;
        width = imageData.width || 256;
        height = imageData.height || 256;
      } else if (imageData.getPixelData && typeof imageData.getPixelData === 'function') {
        pixelData = imageData.getPixelData();
        width = imageData.columns || imageData.width || 256;
        height = imageData.rows || imageData.height || 256;
      } else if (imageData.dataSet && imageData.dataSet.pixelData) {
        // 多帧DICOM数据结构
        pixelData = imageData.dataSet.pixelData;
        width = imageData.columns || 256;
        height = imageData.rows || 256;
        console.log(`使用多帧DICOM像素数据: ${width}x${height}, 数据长度: ${pixelData.length}`);
      } else if (imageData.dataset) {
        // DICOM数据集
        const dataset = imageData.dataset;
        if (dataset.PixelData) {
          pixelData = dataset.PixelData;
          width = dataset.Columns || 256;
          height = dataset.Rows || 256;
        }
      } else if (imageData.imageId) {
        // 这是一个通过URL加载的图像，需要从cache获取或提取像素数据
        const cacheKey = imageData.imageId;
        
        if (pixelDataCache.has(cacheKey)) {
          const cachedData = pixelDataCache.get(cacheKey);
          pixelData = cachedData.pixelData;
          width = cachedData.width;
          height = cachedData.height;
        } else {
          try {
            const extractedData = await getPixelDataFromImage(imageData.imageId);
            setPixelDataCache(prev => new Map(prev.set(cacheKey, extractedData)));
            pixelData = extractedData.pixelData;
            width = extractedData.width;
            height = extractedData.height;
          } catch (error) {
            console.warn('从图像URL提取像素数据失败:', error);
            return 0;
          }
        }
      }

      if (!pixelData) {
        console.warn('无法获取像素数据', {
          imageDataKeys: Object.keys(imageData),
          hasDataSet: !!imageData.dataSet,
          dataSetKeys: imageData.dataSet ? Object.keys(imageData.dataSet) : []
        });
        return 0;
      }
      
      // 边界检查
      if (x < 0 || x >= width || y < 0 || y >= height) {
        return 0;
      }
      
      const index = y * width + x;
      
      if (index >= pixelData.length) {
        return 0;
      }
      
      let value = 0;
      if (pixelData instanceof Uint16Array || pixelData instanceof Int16Array ||
          pixelData instanceof Uint8Array || pixelData instanceof Int8Array ||
          pixelData instanceof Float32Array || pixelData instanceof Float64Array) {
        value = pixelData[index];
      } else if (Array.isArray(pixelData)) {
        value = pixelData[index];
      } else {
        console.warn('未知的像素数据格式:', typeof pixelData);
        return 0;
      }
      
      // 应用图像翻转逻辑
      if (enableInvert && !isNaN(value)) {
        // 创建缓存键来标识这个像素数据
        const dataKey = `${width}_${height}_${pixelData.constructor.name}_${pixelData.length}`;
        
        let maxValue;
        if (pixelDataMaxValues.has(dataKey)) {
          maxValue = pixelDataMaxValues.get(dataKey);
        } else {
          // 计算并缓存最大值
          if (pixelData instanceof Uint16Array || pixelData instanceof Int16Array) {
            maxValue = 65535; // 16位
          } else if (pixelData instanceof Uint8Array || pixelData instanceof Int8Array) {
            maxValue = 255; // 8位
          } else if (pixelData instanceof Float32Array || pixelData instanceof Float64Array) {
            // 对于浮点数据，找到实际的最大值
            maxValue = Math.max(...pixelData);
          } else {
            maxValue = 255; // 默认8位
          }
          
          // 缓存最大值
          setPixelDataMaxValues(prev => new Map(prev.set(dataKey, maxValue)));
        }
        
        value = maxValue - value;
        
        // 在第一个像素时输出翻转信息（避免过多日志）
        if (x === 0 && y === 0) {
          console.log(`图像翻转已启用: 最大值=${maxValue}, 原始值=${value + maxValue}, 翻转后值=${value}`);
        }
      }
      
      return isNaN(value) ? 0 : value;
    } catch (error) {
      console.error('获取像素值失败:', error);
      return 0;
    }
  };

  // 获取区域平均值
  const getRegionAverageValue = async (imageData, region) => {
    try {
      let sum = 0;
      let count = 0;
      
      const width = imageData?.columns || imageData?.width || 256;
      const height = imageData?.rows || imageData?.height || 256;
      
      const startX = Math.max(0, Math.floor(region.x));
      const endX = Math.min(width, Math.ceil(region.x + region.width));
      const startY = Math.max(0, Math.floor(region.y));
      const endY = Math.min(height, Math.ceil(region.y + region.height));
      
      for (let y = startY; y < endY; y++) {
        for (let x = startX; x < endX; x++) {
          const value = await getPixelValue(imageData, x, y);
          sum += value;
          count++;
        }
      }
      
      const average = count > 0 ? sum / count : 0;
      console.log(`区域平均值计算: 区域${startX},${startY}-${endX},${endY}, 平均值: ${average}`);
      return average;
    } catch (error) {
      console.error('获取区域平均值失败:', error);
      return 0;
    }
  };

  // 使用射线法判断点是否在轮廓内部
  const isPointInContour = (point, contourPath) => {
    if (contourPath.length < 3) return false;
    
    let isInside = false;
    const { x, y } = point;
    
    for (let i = 0, j = contourPath.length - 1; i < contourPath.length; j = i++) {
      const xi = contourPath[i].x;
      const yi = contourPath[i].y;
      const xj = contourPath[j].x;
      const yj = contourPath[j].y;
      
      if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
        isInside = !isInside;
      }
    }
    
    return isInside;
  };

  // 获取轮廓内平均值
  const getContourAverageValue = async (imageData, contour) => {
    try {
      let sum = 0;
      let count = 0;
      
      const width = imageData?.columns || imageData?.width || 256;
      const height = imageData?.rows || imageData?.height || 256;
      const { bounds, path } = contour;
      
      // 使用边界框限制扫描范围
      const startX = Math.max(0, Math.floor(bounds.minX));
      const endX = Math.min(width, Math.ceil(bounds.maxX));
      const startY = Math.max(0, Math.floor(bounds.minY));
      const endY = Math.min(height, Math.ceil(bounds.maxY));
      
      console.log(`轮廓扫描范围: (${startX},${startY}) 到 (${endX},${endY})`);
      
      // 扫描边界框内的所有像素
      for (let y = startY; y < endY; y++) {
        for (let x = startX; x < endX; x++) {
          // 检查当前像素是否在轮廓内
          if (isPointInContour({ x, y }, path)) {
            const value = await getPixelValue(imageData, x, y);
            sum += value;
            count++;
          }
        }
      }
      
      const average = count > 0 ? sum / count : 0;
      console.log(`轮廓平均值计算: 扫描 ${(endX-startX)*(endY-startY)} 像素, 轮廓内 ${count} 像素, 平均值: ${average}`);
      return average;
    } catch (error) {
      console.error('获取轮廓平均值失败:', error);
      return 0;
    }
  };

  // 计算统计信息（使用与ImageProcessor一致的算法）
  const calculateStatistics = (timeData, signalData) => {
    if (!signalData || signalData.length === 0) {
      return { peak: 0.0, ttp: 0.0, auc: 0.0 };
    }

    try {
      // 过滤有效数据
      const validSignals = signalData.filter(v => !isNaN(v) && isFinite(v));
      if (validSignals.length === 0) {
        return { peak: 0.0, ttp: 0.0, auc: 0.0 };
      }

      // 使用ParameterCalculator进行统一计算
      parameterCalculator.setTimeArray(timeData);
      const basicStats = parameterCalculator.calculateBasicStatistics(signalData, timeData);
      
      // 返回ParameterCalculator计算的结果
      return basicStats;
    } catch (error) {
      console.error('统计计算失败:', error);
      return { peak: 0.0, ttp: 0.0, auc: 0.0 };
    }
  };

  // 计算TDC数据
  const calculateTDCData = async () => {
    try {
      console.log('=== 开始计算TDC数据 ===');
      console.log('图像数量:', dicomData.images.length);
      console.log('标记数量:', markers.length);
      console.log('帧范围设置:', frameRange);
      
      const visibleMarkers = markers.filter(marker => marker.visible !== false);
      
      // 确定实际的帧范围（从0开始的索引）
      const startFrameIndex = Math.max(0, frameRange.start - 1); // 转换为0基索引
      const endFrameIndex = Math.min(dicomData.images.length - 1, frameRange.end - 1); // 转换为0基索引
      
      console.log(`实际处理帧范围: ${startFrameIndex} - ${endFrameIndex} (共 ${endFrameIndex - startFrameIndex + 1} 帧)`);
      
      const tdcData = await Promise.all(visibleMarkers.map(async (marker, markerIndex) => {
        console.log(`\n处理标记 ${markerIndex + 1}: ${marker.name} (${marker.type})`);
        
        const dataPoints = [];

        // 只收集指定帧范围内的数据
        for (let timeIndex = startFrameIndex; timeIndex <= endFrameIndex; timeIndex++) {
          const image = dicomData.images[timeIndex];
          let signalValue = 0;

          if (marker.type === 'point') {
            // 点标记 - 获取单点信号值
            signalValue = await getPixelValue(image, marker.x, marker.y);
            if (timeIndex < 3) {
              console.log(`帧${timeIndex}: 点(${marker.x},${marker.y}) = ${signalValue}`);
            }
          } else if (marker.type === 'region') {
            // 区域标记 - 计算区域平均值
            signalValue = await getRegionAverageValue(image, marker.region);
            if (timeIndex < 3) {
              console.log(`帧${timeIndex}: 区域平均值 = ${signalValue}`);
            }
          } else if (marker.type === 'contour') {
            // 轮廓标记 - 计算轮廓内平均值
            signalValue = await getContourAverageValue(image, marker.contour);
            if (timeIndex < 3) {
              console.log(`帧${timeIndex}: 轮廓平均值 = ${signalValue}`);
            }
          }

          // 处理时间信息 - 优先使用DICOM帧率信息
          // 计算相对于起始帧的时间索引
          const relativeTimeIndex = timeIndex - startFrameIndex;
          let timeValue = relativeTimeIndex; // 默认使用相对帧索引
          
          // 优先检查DICOM帧率信息（0008,2144）
          if (dicomData.metadata?.frameRate && parseFloat(dicomData.metadata.frameRate) > 0) {
            const frameRate = parseFloat(dicomData.metadata.frameRate);
            const timeInterval = 1.0 / frameRate; // 每帧的时间间隔（秒）
            timeValue = relativeTimeIndex * timeInterval; // 使用相对时间索引
            if (timeIndex === startFrameIndex) {
              console.log(`使用DICOM帧率: ${frameRate} fps, 时间间隔: ${timeInterval.toFixed(3)}s, 起始帧: ${startFrameIndex}`);
            }
          }
          // 尝试从acquisitionTime获取真实时间
          else if (image.acquisitionTime) {
            const timeStr = image.acquisitionTime.toString();
            
            // 如果是DICOM时间格式 (HHMMSS.FFFFFF)
            if (timeStr.length >= 6 && /^\d+\.?\d*$/.test(timeStr)) {
              const hours = parseInt(timeStr.substr(0, 2) || '0');
              const minutes = parseInt(timeStr.substr(2, 2) || '0');
              const seconds = parseFloat(timeStr.substr(4) || '0');
              timeValue = hours * 3600 + minutes * 60 + seconds;
            } else {
              // 尝试直接解析为数字
              const parsed = parseFloat(timeStr);
              if (!isNaN(parsed) && isFinite(parsed)) {
                timeValue = parsed;
              }
            }
          }
          // 检查其他时间相关标签
          else if (dicomData.metadata?.frameTime && parseFloat(dicomData.metadata.frameTime) > 0) {
            const frameTimeMs = parseFloat(dicomData.metadata.frameTime);
            timeValue = relativeTimeIndex * (frameTimeMs / 1000); // 转换为秒，使用相对时间索引
            if (timeIndex === startFrameIndex) {
              console.log(`使用Frame Time: ${frameTimeMs}ms 间隔, 起始帧: ${startFrameIndex}`);
            }
          }
          else if (dicomData.metadata?.temporalResolution && parseFloat(dicomData.metadata.temporalResolution) > 0) {
            const temporalResMs = parseFloat(dicomData.metadata.temporalResolution);
            timeValue = relativeTimeIndex * (temporalResMs / 1000); // 转换为秒，使用相对时间索引
            if (timeIndex === startFrameIndex) {
              console.log(`使用Temporal Resolution: ${temporalResMs}ms 间隔, 起始帧: ${startFrameIndex}`);
            }
          }
          else {
            // 兜底：使用默认1秒间隔
            timeValue = relativeTimeIndex * 1.0; // 使用相对时间索引
            if (timeIndex === startFrameIndex) {
              console.log(`使用默认1秒间隔, 起始帧: ${startFrameIndex}`);
            }
          }

          dataPoints.push({
            time: timeValue,
            signal: signalValue,
            frameIndex: timeIndex
          });
        }

        // 按时间排序数据点
        dataPoints.sort((a, b) => a.time - b.time);
        
        // 计算相对时间（从第一帧开始）
        const baseTime = dataPoints.length > 0 ? dataPoints[0].time : 0;
        const timeData = dataPoints.map((point, index) => {
          // 如果时间值看起来像绝对时间戳，计算相对时间
          if (point.time > 1000000) { // 可能是时间戳
            return (point.time - baseTime) / 1000; // 转换为秒
          } else if (point.time >= baseTime) {
            return point.time - baseTime; // 相对时间
          } else {
            return index; // 兜底：使用索引
          }
        });
        
        const signalData = dataPoints.map(point => point.signal);

        console.log(`标记 ${marker.name} 时间数据范围:`, {
          min: Math.min(...timeData),
          max: Math.max(...timeData),
          count: timeData.length
        });
        
        console.log(`标记 ${marker.name} 信号数据范围:`, {
          min: Math.min(...signalData),
          max: Math.max(...signalData),
          avg: signalData.reduce((a, b) => a + b, 0) / signalData.length
        });

        return {
          id: marker.id,
          name: marker.name,
          type: marker.type,
          color: marker.color,
          timeData,
          signalData,
          statistics: calculateStatistics(timeData, signalData)
        };
      }));

      console.log('=== TDC数据计算完成 ===');
      console.log('生成的数据集数量:', tdcData.length);
      
      setChartData(tdcData);
      
      // 通知外部组件chartData已更新
      if (onChartDataUpdate) {
        onChartDataUpdate(tdcData);
      }
    } catch (error) {
      console.error('计算TDC数据失败:', error);
      const emptyData = [];
      setChartData(emptyData);
      
      // 通知外部组件chartData已清空
      if (onChartDataUpdate) {
        onChartDataUpdate(emptyData);
      }
    }
  };

  // 绘制图表
  const drawChart = () => {
    const canvas = canvasRef.current;
    if (!canvas || chartData.length === 0) {
      console.warn('Canvas或数据不可用');
      return;
    }

    console.log('=== 开始绘制图表 ===');
    console.log('Canvas元素:', canvas);
    console.log('容器尺寸:', containerSize);
    console.log('图表数据:', chartData.length, '个数据集');

    const ctx = canvas.getContext('2d');
    const { width, height } = containerSize;
    
    // 设置canvas尺寸
    canvas.width = width;
    canvas.height = height;
    
    console.log('Canvas尺寸设置:', { width, height });

    // 清空画布
    ctx.fillStyle = '#0d1117';
    ctx.fillRect(0, 0, width, height);

    // 设置边距
    const margin = { top: 30, right: 40, bottom: 60, left: 60 };
    const chartWidth = width - margin.left - margin.right;
    const chartHeight = height - margin.top - margin.bottom;

    if (chartWidth <= 0 || chartHeight <= 0) {
      console.warn('图表区域太小:', { chartWidth, chartHeight });
      return;
    }

    // 计算数据范围
    let minTime = Infinity, maxTime = -Infinity;
    let minSignal = Infinity, maxSignal = -Infinity;

    chartData.forEach(data => {
      data.timeData.forEach(time => {
        if (!isNaN(time) && isFinite(time)) {
          minTime = Math.min(minTime, time);
          maxTime = Math.max(maxTime, time);
        }
      });
      data.signalData.forEach(signal => {
        if (!isNaN(signal) && isFinite(signal)) {
          minSignal = Math.min(minSignal, signal);
          maxSignal = Math.max(maxSignal, signal);
        }
      });
    });

    console.log('数据范围:', { 
      time: [minTime, maxTime], 
      signal: [minSignal, maxSignal] 
    });

    // 如果数据范围无效，使用默认值
    if (!isFinite(minTime) || !isFinite(maxTime)) {
      minTime = 0;
      maxTime = 10;
    }
    if (!isFinite(minSignal) || !isFinite(maxSignal)) {
      minSignal = 0;
      maxSignal = 100;
    }

    // 添加一些边距到数据范围
    const timeRange = maxTime - minTime || 1;
    const signalRange = maxSignal - minSignal || 1;
    
    minTime -= timeRange * 0.05;
    maxTime += timeRange * 0.05;
    minSignal -= signalRange * 0.05;
    maxSignal += signalRange * 0.05;

    // 坐标转换函数
    const xScale = (time) => margin.left + ((time - minTime) / (maxTime - minTime)) * chartWidth;
    const yScale = (signal) => margin.top + ((maxSignal - signal) / (maxSignal - minSignal)) * chartHeight;

    // 绘制网格
    ctx.strokeStyle = '#30363d';
    ctx.lineWidth = 1;
    
    // 垂直网格线
    for (let i = 0; i <= 10; i++) {
      const x = margin.left + (i / 10) * chartWidth;
      ctx.beginPath();
      ctx.moveTo(x, margin.top);
      ctx.lineTo(x, margin.top + chartHeight);
      ctx.stroke();
    }
    
    // 水平网格线
    for (let i = 0; i <= 10; i++) {
      const y = margin.top + (i / 10) * chartHeight;
      ctx.beginPath();
      ctx.moveTo(margin.left, y);
      ctx.lineTo(margin.left + chartWidth, y);
      ctx.stroke();
    }

    // 绘制坐标轴
    ctx.strokeStyle = '#c9d1d9';
    ctx.lineWidth = 2;
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(margin.left, margin.top + chartHeight);
    ctx.lineTo(margin.left + chartWidth, margin.top + chartHeight);
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(margin.left, margin.top);
    ctx.lineTo(margin.left, margin.top + chartHeight);
    ctx.stroke();

    // 绘制轴标签
    ctx.fillStyle = '#c9d1d9';
    ctx.font = '12px -apple-system, BlinkMacSystemFont, sans-serif';
    ctx.textAlign = 'center';
    
    // X轴标签
    for (let i = 0; i <= 5; i++) {
      const time = minTime + (i / 5) * (maxTime - minTime);
      const x = xScale(time);
      ctx.fillText(time.toFixed(1), x, height - 15);
    }
    
    // Y轴标签
    ctx.textAlign = 'right';
    for (let i = 0; i <= 5; i++) {
      const signal = minSignal + (i / 5) * (maxSignal - minSignal);
      const y = yScale(signal);
      ctx.fillText(signal.toFixed(0), margin.left - 10, y + 4);
    }

    // 绘制曲线
    chartData.forEach((data, dataIndex) => {
      console.log(`绘制曲线 ${dataIndex + 1}: ${data.name}`, {
        color: data.color,
        points: data.timeData.length
      });
      
      ctx.strokeStyle = data.color;
      ctx.lineWidth = 3;
      ctx.beginPath();

      let hasValidPoint = false;
      data.timeData.forEach((time, index) => {
        const signal = data.signalData[index];
        
        if (isNaN(time) || isNaN(signal) || !isFinite(time) || !isFinite(signal)) {
          return;
        }
        
        const x = xScale(time);
        const y = yScale(signal);
        
        if (!hasValidPoint) {
          ctx.moveTo(x, y);
          hasValidPoint = true;
        } else {
          ctx.lineTo(x, y);
        }
      });

      if (hasValidPoint) {
        ctx.stroke();

        // 绘制数据点
        ctx.fillStyle = data.color;
        data.timeData.forEach((time, index) => {
          const signal = data.signalData[index];
          
          if (isNaN(time) || isNaN(signal) || !isFinite(time) || !isFinite(signal)) {
            return;
          }
          
          const x = xScale(time);
          const y = yScale(signal);
          
          ctx.beginPath();
          ctx.arc(x, y, 4, 0, 2 * Math.PI);
          ctx.fill();
        });
      }
    });

    // 绘制轴标题
    ctx.fillStyle = '#c9d1d9';
    ctx.font = '14px -apple-system, BlinkMacSystemFont, sans-serif';
    ctx.textAlign = 'center';
    
    // X轴标题
    ctx.fillText('时间 (s)', width / 2, height - 10);
    
    // Y轴标题
    ctx.save();
    ctx.translate(20, height / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText('信号强度', 0, 0);
    ctx.restore();

    console.log('=== 图表绘制完成 ===');
  };

  return (
    <div className="tdc-analyzer" ref={containerRef}>
      <div className="analyzer-header">
        <h3>TDC分析</h3>
        <div className="marker-count">
          {markers.length} 个标记 | 
          可见: {markers.filter(m => m.visible !== false).length} |
          帧范围: {frameRange.start}-{frameRange.end}
        </div>
        {/* 显示时间间隔信息 */}
        {dicomData && (
          <div className="time-interval-info">
            {dicomData.metadata?.frameRate && parseFloat(dicomData.metadata.frameRate) > 0 ? (
              <span className="time-info">
                📊 帧率: {parseFloat(dicomData.metadata.frameRate).toFixed(1)} fps 
                (间隔: {(1.0 / parseFloat(dicomData.metadata.frameRate)).toFixed(3)}s)
              </span>
            ) : dicomData.metadata?.frameTime && parseFloat(dicomData.metadata.frameTime) > 0 ? (
              <span className="time-info">
                ⏱️ 帧时间: {parseFloat(dicomData.metadata.frameTime).toFixed(1)}ms
              </span>
            ) : dicomData.metadata?.temporalResolution && parseFloat(dicomData.metadata.temporalResolution) > 0 ? (
              <span className="time-info">
                🕐 时间分辨率: {parseFloat(dicomData.metadata.temporalResolution).toFixed(1)}ms
              </span>
            ) : (
              <span className="time-info default">
                ⚠️ 使用默认1秒间隔
              </span>
            )}
          </div>
        )}
      </div>

      {chartData.length > 0 ? (
        <div className="tdc-chart-container">
          <canvas
            ref={canvasRef}
            className="tdc-chart"
            style={{ width: '100%', height: '100%' }}
          />
        </div>
      ) : (
        <div className="no-data">
          <div className="no-data-icon">📊</div>
          <p>请在左侧图像上添加标记点来分析TDC曲线</p>
          <div className="instruction-list">
            <div>• 左键点击添加点标记</div>
            <div>• Ctrl+左键拖拽添加矩形区域标记</div>
            <div>• Shift+左键拖拽绘制自由轮廓标记</div>
            <div>• 右键删除标记</div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TDCAnalyzer;